package com.czy.owner.ui.workorder;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.czy.owner.R;
import com.czy.owner.alipay.PayResult;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.PickCardEntity;
import com.czy.owner.entity.PrePayBalancePaymentModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.setting.ForgetPaidPasswordActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.wxapi.WXPayEntryActivity;
import com.google.gson.Gson;
import com.input.password.ui.InputPwdView;
import com.input.password.ui.MyInputPwdUtil;
import com.input.password.ui.PaidErrorDialog;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangyang on 2016/6/17.
 * 支付尾款
 */
public class PaidEndOfPaymentActivity extends BaseActivity {
    @BindView(R.id.tv_all_jine)
    TextView tvAllJine;//总金额
    @BindView(R.id.tv_had_paid_dingjin)
    TextView tvHadPaidDingJin;//已支付
    @BindView(R.id.tv_end_of_payment)
    TextView tvEndOfPayment;//尾款金额
    @BindView(R.id.cb_online_paid)
    CheckBox cbOnlinePaid;//线下支付
    @BindView(R.id.tv_coupon)
    TextView tvCoupon;//优惠券
    @BindView(R.id.tv_project_card)
    TextView tvProjectCard;//项目卡
    @BindView(R.id.tv_use_yue)
    TextView tvUseYue;//使用余额
    @BindView(R.id.cb_yue)
    CheckBox cbYue;//使用余额CheckBox
    @BindView(R.id.tv_sdk_paid_tip)
    TextView tvSdkPaidTip;//第三方支付还需多少
    @BindView(R.id.cb_zhifubao)
    CheckBox cbZhiFuBao;//支付宝CheckBox
    @BindView(R.id.cb_weixin)
    CheckBox cbWeiXin;//微信CheckBox

    private int storeId = 0;
    private String orderNumber;
    private static final int SDK_PAY_FLAG = 1;//支付
    private String selectedPaidType = "aliPay";
    private double realityPaid; //实际支付
//    private String useStoreBalance = "false";
    private boolean isUseStoreBalance = false;

    private double storeBalance;

    private MyInputPwdUtil myInputPwdUtil;

    private PrePayBalancePaymentModel paymentData = null;

    private static final int COUPONS_LIST = 0X11;//券列表
    private static final int CARDS_LIST = 0X12;//卡列表

    private ArrayList<String> cardList = new ArrayList<>(), couponList = new ArrayList<>();
    private List<PickCardEntity> pickCardEntityList = new ArrayList<>();

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        updataUserInfo();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PhoneUtils.ShowToastMessage(PaidEndOfPaymentActivity.this, "支付失败");
                    }
                    break;
                }


            }
        }

    };

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_paid_endof_payment;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.paid_end_of_payment);
        RxBus.getDefault().register(this);
        orderNumber = getIntent().getStringExtra("orderNumber");
        storeId = getIntent().getIntExtra("storeId", 0);
        userPayInfoData();
        myInputPwdUtil = new MyInputPwdUtil(this);
        myInputPwdUtil.getMyInputDialogBuilder().setAnimStyle(R.style.ActionSheetDialogAnimation);
        myInputPwdUtil.setListener(new InputPwdView.InputPwdListener() {
            @Override
            public void hide() {
                myInputPwdUtil.hide();
            }

            @Override
            public void forgetPwd() {
                startActivity(new Intent(PaidEndOfPaymentActivity.this, ForgetPaidPasswordActivity.class));
            }

            @Override
            public void finishPwd(String pwd) {
                bannceVerifyPayPassword(pwd);
            }
        });
    }

    @Override
    protected void updateViews() {

    }

    private void bannceVerifyPayPassword(String payPassword) {
        String url = Constants.APP_API_BASE + Constants.OWN_VERIFYPAYPASSWORD;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(PaidEndOfPaymentActivity.this).getSession());
        params.addBodyParameter("payPassword", payPassword);
        params.addBodyParameter("userId", UserHelper.getInstance().getUserInfoModel(PaidEndOfPaymentActivity.this).getUserId() + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                int count = JsonUtil.getJsonValuesInt(result, "data");
                if (flag) {
                    myInputPwdUtil.hide();
                    payEndOfPayMent();
                } else {
                    switch (count) {
                        case 1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(PaidEndOfPaymentActivity.this, myInputPwdUtil);
                            break;
                        case 2:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(PaidEndOfPaymentActivity.this, myInputPwdUtil);
                            break;
                        case 3:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(PaidEndOfPaymentActivity.this, exp);
                            break;
                        case -1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(PaidEndOfPaymentActivity.this, exp);
                            break;
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void userPayInfoData() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_PREPAYBALANCEPAYMENT;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        params.addBodyParameter("orderNumber", orderNumber);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                MyLog.e("yang","支付尾款=="+result);
                String data = PhoneUtils.checkResponseFlag(PaidEndOfPaymentActivity.this, result);
                try {
                    if (data != null) {
                        paymentData = new Gson().fromJson(data, PrePayBalancePaymentModel.class);
                        //Collections.reverse(paymentData.getCouponsList());
                        Collections.sort(paymentData.getCouponsList(), new Comparator<PrePayBalancePaymentModel.CouponsListBean>() {
                            @Override
                            public int compare(PrePayBalancePaymentModel.CouponsListBean lhs, PrePayBalancePaymentModel.CouponsListBean rhs) {
                                if (lhs.getMinimum() < rhs.getMinimum()) {
                                    return -1;
                                } else if (lhs.getMinimum() == rhs.getMinimum()) {
                                    return 0;
                                } else {
                                    return 1;
                                }
                            }
                        });

                        storeBalance = paymentData.getStoreBalance();//账户余额
                        tvAllJine.setText("¥ " + String.format("%.2f", paymentData.getTotalPrice()));//订单总价
                        tvHadPaidDingJin.setText("¥ " + String.format("%.2f", paymentData.getPayedDepositAmount()));//已付定金
                        tvEndOfPayment.setText("¥ " + String.format("%.2f", paymentData.getTotalPrice() - paymentData.getPayedDepositAmount()));//尾款金额
                        tvUseYue.setText("¥ " + String.format("%.2f", storeBalance));//账户余额

                        paymentData.setTailAmount(paymentData.getTotalPrice() - paymentData.getPayedDepositAmount());


                        showCount(2);


                        checkEndOfPayment();
                        realityPaid = storeBalance - paymentData.getTailAmount();//实际支付

                        if (storeBalance == 0) {
                            cbYue.setClickable(false);
                        } else {
                            cbYue.setClickable(true);
                        }

                        if (realityPaid >= 0) {
                            isUseStoreBalance = true;
                        } else {
                            isUseStoreBalance = false;
                        }

                    }
                } catch (Exception e) {
                    Log.e("King", "解析失败!");
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


    //余额支付
    @OnClick(R.id.cb_yue)
    public void cbYuEOnClick(View view) {
        if (cbYue.isChecked()) {
            double dEndOfAmount = 0.00;
            String sEndOfAmount = tvEndOfPayment.getText().toString().trim();
            dEndOfAmount = Double.parseDouble(sEndOfAmount.substring(1, sEndOfAmount.length()));

            if (storeBalance - dEndOfAmount >= 0) {  //当门店余额大于等于支付尾款时
                cbZhiFuBao.setChecked(false);
                cbWeiXin.setChecked(false);
                cbYue.setChecked(true);
                tvSdkPaidTip.setVisibility(View.GONE);
            } else {
                tvSdkPaidTip.setVisibility(View.VISIBLE);
                tvSdkPaidTip.setText("余额可支付¥" + String.format("%.2f", storeBalance) + ",还需第三方支付¥" + String.format("%.2f", Math.abs(storeBalance - dEndOfAmount)));
            }
//            useStoreBalance = "true";
        } else {
            tvSdkPaidTip.setVisibility(View.GONE);
//            useStoreBalance = "false";
        }
    }

    //支付宝支付
    @OnClick(R.id.cb_zhifubao)
    public void cbZhiFuBaoOnClick(View view) {

        if (tvSdkPaidTip.getVisibility() == View.VISIBLE && !cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(true);
            return;
        }

        double dEndOfAmount = 0.00;
        String sEndOfAmount = tvEndOfPayment.getText().toString().trim();
        dEndOfAmount = Double.parseDouble(sEndOfAmount.substring(1, sEndOfAmount.length()));

        if (cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(false);
            selectedPaidType = "aliPay";
            if (storeBalance - dEndOfAmount >= 0 && cbYue.isChecked() == true) {
                cbYue.setChecked(false);
            }
        } else {
            selectedPaidType = "11";
        }


    }

    //微信支付
    @OnClick(R.id.cb_weixin)
    public void cbWeiXinOnClick(View view) {

        if (tvSdkPaidTip.getVisibility() == View.VISIBLE && !cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(true);
            return;
        }
        double dEndOfAmount = 0.00;
        String sEndOfAmount = tvEndOfPayment.getText().toString().trim();
        dEndOfAmount = Double.parseDouble(sEndOfAmount.substring(1, sEndOfAmount.length()));

        if (cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(false);
            selectedPaidType = "wxPay";
            if (storeBalance - dEndOfAmount >= 0 && cbYue.isChecked() == true) {
                cbYue.setChecked(false);
            }
        } else {
            selectedPaidType = "22";
        }


    }

    //确认支付
    @OnClick(R.id.btn_sure_paid)
    public void btnSureOnClick(View view) {
        if (cbYue.isChecked()) {
            myInputPwdUtil.show();
        } else {
            payEndOfPayMent();
        }
    }


    private void payEndOfPayMent() {
        mLoadView.ShowLoadView();
        String couponsUserWalletid = "";
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_PAYBALANCEPAYMENT;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        params.addBodyParameter("orderNumber", orderNumber);
        if (selectedPaidType.equals("aliPay") || selectedPaidType.equals("wxPay")) {
            params.addBodyParameter("payType", selectedPaidType);
        }

        StringBuilder sbUserWalletid = new StringBuilder();

        if (tvProjectCard.getText().toString().trim().contains("￥")) {
            if (pickCardEntityList != null && pickCardEntityList.size() > 0) {
                for (int i = 0; i < pickCardEntityList.size(); i++) {
                    sbUserWalletid.append(pickCardEntityList.get(i).getUserWalletId() + ",");
                }
            }
        }

        if (tvCoupon.getText().toString().trim().contains("￥")) {
            if (couponList != null && couponList.size() > 0) {
                couponsUserWalletid = couponList.get(0);
            }
        }


        String userWalletIds = sbUserWalletid.toString() + couponsUserWalletid;
        if (userWalletIds.endsWith(",")) {
            userWalletIds = userWalletIds.substring(0, userWalletIds.length() - 1);
        }

        params.addBodyParameter("userWalletIds", userWalletIds);
        params.addBodyParameter("useStoreBalance", cbYue.isChecked()+"");

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(PaidEndOfPaymentActivity.this, result);
                if (data.equals("")) {
                    updataUserInfo();
                } else {
                    if (selectedPaidType.equals("aliPay")) {
                        aliPayPaid(data);
                    } else if (selectedPaidType.equals("wxPay")) {
                        if (isWXAppInstalledAndSupported()) {
                            WXPayEntryActivity.wxPayPaidStart(PaidEndOfPaymentActivity.this, data, "支付尾款成功");
                        } else {
                            PhoneUtils.ShowToastMessage(PaidEndOfPaymentActivity.this, getString(R.string.isInstallwx));
                        }

                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    //判断是否安装微信客户端
    public boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(WXPayEntryActivity.APP_ID);
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled() && msgApi.isWXAppSupportAPI();
        return sIsWXAppInstalledAndSupported;
    }

    private void aliPayPaid(final String data) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PaidEndOfPaymentActivity.this);
                // 调用支付接口，获取支付结果
                Map<String, String> result = alipay.payV2(data, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //    跳转优惠券
    @OnClick(R.id.relative_discount_coupon)
    public void discountCouponOnClick(View view) {
        if (paymentData == null) {
            PhoneUtils.ShowToastMessage(PaidEndOfPaymentActivity.this, "订单数据加载中,请稍候再试!");
//        } else if (couponsCount == 0) {
        } else if (tvCoupon.getText().toString().trim().equals("无可用优惠券")) {
            PhoneUtils.ShowToastMessage(PaidEndOfPaymentActivity.this, "无可用优惠券!");
        } else {
            Intent ti = new Intent(PaidEndOfPaymentActivity.this, PickCouponActivity.class);
            ti.putExtra(Constants.TRANSMISSION_CONTENT_KEY, paymentData);
            startActivityForResult(ti, COUPONS_LIST);
        }
    }

    //  跳转项目卡
    @OnClick(R.id.relative_project_card)
    public void projectCardOnClick(View view) {
        if (paymentData == null) {
            PhoneUtils.ShowToastMessage(PaidEndOfPaymentActivity.this, "订单数据加载中,请稍候再试!");
//        } else if (cardsCount == 0) {
        } else if (tvProjectCard.getText().toString().trim().equals("无可用卡项")) {
            PhoneUtils.ShowToastMessage(PaidEndOfPaymentActivity.this, "无可用卡项!");
        } else {
            Intent ti = new Intent(PaidEndOfPaymentActivity.this, PickCardActivity.class);
            ti.putExtra(Constants.TRANSMISSION_CONTENT_KEY, paymentData);
            startActivityForResult(ti, CARDS_LIST);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


//        卡返回
        if (requestCode == CARDS_LIST && resultCode == RESULT_OK) {
            cardList = data.getStringArrayListExtra("PICK_RESULT");
            pickCardEntityList = (List<PickCardEntity>) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
            double mCardMoney = 0.00;

            if (pickCardEntityList == null || pickCardEntityList.size() == 0) {
                paymentData.setTailAmount(paymentData.getTotalPrice() - paymentData.getPayedDepositAmount());
                showCount(0);

                if (tvCoupon.getText().toString().trim().contains("￥")) {
                    if (paymentData.getCouponsList().size() > 0) {
                        double mCounponMenoy = 0.00;
                        for (int j = 0; j < paymentData.getCouponsList().size(); j++) {
                            if (paymentData.getCouponsList().get(j).getUserWalletId() == Integer.valueOf(couponList.get(0))) {
                                if (paymentData.getCouponsList().get(j).getCouponsType().equals("cashVoucher")) { //返回现金券
                                    mCounponMenoy = paymentData.getCouponsList().get(j).getDenomination();
                                } else if (paymentData.getCouponsList().get(j).getCouponsType().equals("discountVoucher")) {//返回折扣券
                                    mCounponMenoy = paymentData.getTailAmount() - paymentData.getTailAmount() * paymentData.getCouponsList().get(j).getDisCount();
                                }
                            }
                        }
                        tvCoupon.setText("-￥" + String.format("%.2f", mCounponMenoy));
                    }


                } else {
                    showCount(1);
                }


            } else {
                for (int i = 0; i < pickCardEntityList.size(); i++) {

                    mCardMoney += pickCardEntityList.get(i).getPrice();
                }
                tvProjectCard.setText("-￥" + String.format("%.2f", mCardMoney));

                //保存尾款
                double dEndOfPayment = paymentData.getTotalPrice() - paymentData.getPayedDepositAmount() - mCardMoney;
                paymentData.setTailAmount(dEndOfPayment);

                //遍历券列表是否可用        尾款>=选择过的券  重新计算    尾款<选择过的券 重置
/////////////////////////////////////////////////////////////////////////////////////////////////////////

                if (couponList != null && couponList.size() > 0) {
                    double mCounponMenoy = 0.00;
                    double miniMun = 0.00;
                    if (paymentData.getCouponsList().size() > 0) {
                        for (int j = 0; j < paymentData.getCouponsList().size(); j++) {
                            if (paymentData.getCouponsList().get(j).getUserWalletId() == Integer.valueOf(couponList.get(0))) {
                                miniMun = paymentData.getCouponsList().get(j).getMinimum();
                                if (paymentData.getCouponsList().get(j).getCouponsType().equals("cashVoucher")) { //返回现金券
                                    mCounponMenoy = paymentData.getCouponsList().get(j).getDenomination();
                                } else if (paymentData.getCouponsList().get(j).getCouponsType().equals("discountVoucher")) {//返回折扣券
                                    mCounponMenoy = paymentData.getTailAmount() - paymentData.getTailAmount() * paymentData.getCouponsList().get(j).getDisCount();
                                }
                            }
                        }
                        if (tvCoupon.getText().toString().contains("￥") && dEndOfPayment >= miniMun) {
                            MyLog.e("yang", "重新计算");
                            tvCoupon.setText("-￥" + String.format("%.2f", mCounponMenoy));
                        } else {
                            MyLog.e("yang", "重置");
                            showCount(1);
                            for (int k = 0; k < paymentData.getCouponsList().size(); k++) {
                                if (!paymentData.getCouponsList().get(k).getCouponsType().equals("serviceVoucher")) {
                                    if (couponList.contains("" + paymentData.getCouponsList().get(k).getUserWalletId())) {
                                        paymentData.getCouponsList().get(k).setPicked(false);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    showCount(1);
                }


                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }


            cardChecked();

        }

        //券返回
        if (requestCode == COUPONS_LIST && resultCode == RESULT_OK) {
            couponList = data.getStringArrayListExtra(Constants.TRANSMISSION_CONTENT_KEY);
            if (couponList == null || couponList.size() == 0) {
                showCount(1);
            } else {
                double mCounponMenoy = 0.00;
                for (int i = 0; i < paymentData.getCouponsList().size(); i++) {
                    if (paymentData.getCouponsList().get(i).getUserWalletId() == Integer.valueOf(couponList.get(0))) {
                        if (paymentData.getCouponsList().get(i).getCouponsType().equals("cashVoucher")) { //返回现金券
                            mCounponMenoy = paymentData.getCouponsList().get(i).getDenomination();
                        } else if (paymentData.getCouponsList().get(i).getCouponsType().equals("discountVoucher")) {//返回折扣券
                            mCounponMenoy = paymentData.getTailAmount() - paymentData.getTailAmount() * paymentData.getCouponsList().get(i).getDisCount();
                        }
                    }
                }
                tvCoupon.setText("-￥" + String.format("%.2f", mCounponMenoy));

                //保存尾款
                double dCardAmount = 0.00;
                if (tvProjectCard.getText().toString().contains("￥")) {
                    String sCardAmount = tvProjectCard.getText().toString().trim();
                    dCardAmount = Double.parseDouble(sCardAmount.substring(2, sCardAmount.length()));
                }
                paymentData.setTailAmount(paymentData.getTotalPrice() - paymentData.getPayedDepositAmount() - dCardAmount);
            }

            couponChecked();

        }

        showEndOnPayment();
    }

    //最后显示尾款
    private void showEndOnPayment() {
        MyLog.e("yang", "尾款==" + paymentData.getTailAmount());
        double dEndOfAmount = paymentData.getTotalPrice() - paymentData.getPayedDepositAmount();//尾款金额
        double dCardAmount = 0.00;
        double dCouponAmount = 0.00;
        if (tvProjectCard.getText().toString().contains("￥")) {
            String sCardAmount = tvProjectCard.getText().toString().trim();
            dCardAmount = Double.parseDouble(sCardAmount.substring(2, sCardAmount.length()));
        }

        if (tvCoupon.getText().toString().contains("￥")) {
            String sCouponAmount = tvCoupon.getText().toString().trim();
            dCouponAmount = Double.parseDouble(sCouponAmount.substring(2, sCouponAmount.length()));
        }

        if (dEndOfAmount <= dCardAmount + dCouponAmount) {
            tvEndOfPayment.setText("￥0.00");
        } else {
            tvEndOfPayment.setText("￥" + String.format("%.2f", dEndOfAmount - dCardAmount - dCouponAmount));//尾款金额
        }
        checkEndOfPayment();
    }

    //显示可用卡可用券
    private void showCount(int type) {
        int cardsCount = 0, couponsCount = 0;
        cardsCount = paymentData.getTimeCardList().size() + paymentData.getCycleCardList().size();
        if (paymentData.getCouponsList().size() > 0) {
            for (int i = 0; i < paymentData.getCouponsList().size(); i++) {

                if (paymentData.getCouponsList().get(i).getCouponsType().equals("serviceVoucher")) {
                    cardsCount++;
                } else if (paymentData.getTailAmount() >= paymentData.getCouponsList().get(i).getMinimum()) {
                    couponsCount++;
                }
            }

        }


//       0 卡  1 券 2全部

        switch (type) {
            case 0:
                if (cardsCount == 0) {
                    tvProjectCard.setText("无可用卡项");
                } else {
                    tvProjectCard.setText(cardsCount + "张卡可用");
                }
                break;
            case 1:

//                if (couponList.size() > 0) {
                couponList.clear();
                couponChecked();
//                }


                if (couponsCount == 0) {
                    tvCoupon.setText("无可用优惠券");
                } else {
                    tvCoupon.setText(couponsCount + "张优惠券可用");
                }


                break;
            case 2:
                if (cardsCount == 0) {
                    tvProjectCard.setText("无可用卡项");
                } else {
                    tvProjectCard.setText(cardsCount + "张卡可用");
                }

//                if (couponList.size() > 0) {
                couponList.clear();
                couponChecked();
//                }

                if (couponsCount == 0) {
                    tvCoupon.setText("无可用优惠券");
                } else {
                    tvCoupon.setText(couponsCount + "张优惠券可用");
                }
                break;


        }


    }


    private void updataUserInfo() {
        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
        Intent intent = new Intent();
        intent.setAction(SubscribeOrdelActivity.orderAction);
        if (SubscribeOrdelActivity.currentId() == 0) {
            intent.putExtra("currentId", 0);
        } else if (SubscribeOrdelActivity.currentId() == 3) {
            intent.putExtra("currentId", 4);
        }
        sendBroadcast(intent);
        RxBus.getDefault().post(Constants.PAID_SUCCESS_ENDOF_PAYMENT,new CommonEvent("详情尾款支付成功"));
        finish();
    }


    @Subscribe(code = Constants.PAID_SUCCESS_ENDOF_PAYMENT, threadMode = ThreadMode.MAIN)
    public void eventPaidSuccess(CommonEvent paidSuccessEvent) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }


    private void checkEndOfPayment() {
        if (tvEndOfPayment.getText().toString().equals("￥0.00")) {
            cbYue.setChecked(false);
            cbYue.setClickable(false);
            cbZhiFuBao.setChecked(false);
            cbZhiFuBao.setClickable(false);
            cbWeiXin.setChecked(false);
            cbWeiXin.setClickable(false);
        } else {
            cbYue.setChecked(false);
            cbYue.setClickable(true);
            cbZhiFuBao.setChecked(true);
            cbZhiFuBao.setClickable(true);
            cbWeiXin.setChecked(false);
            cbWeiXin.setClickable(true);
        }
    }


    private void cardChecked() {
        for (int i = 0; i < paymentData.getTimeCardList().size(); i++) {
            if (cardList.contains("" + paymentData.getTimeCardList().get(i).getUserWalletId())) {
                paymentData.getTimeCardList().get(i).setPicked(true);
            } else {
                paymentData.getTimeCardList().get(i).setPicked(false);
            }
        }
        for (int i = 0; i < paymentData.getCycleCardList().size(); i++) {
            if (cardList.contains("" + paymentData.getCycleCardList().get(i).getUserWalletId())) {
                paymentData.getCycleCardList().get(i).setPicked(true);
            } else {
                paymentData.getCycleCardList().get(i).setPicked(false);
            }
        }
        for (int i = 0; i < paymentData.getCouponsList().size(); i++) {
            if (paymentData.getCouponsList().get(i).getCouponsType().equals("serviceVoucher")) {
                if (cardList.contains("" + paymentData.getCouponsList().get(i).getUserWalletId())) {
                    paymentData.getCouponsList().get(i).setPicked(true);
                } else {
                    paymentData.getCouponsList().get(i).setPicked(false);
                }
            }
        }
    }

    private void couponChecked() {
        for (int i = 0; i < paymentData.getCouponsList().size(); i++) {
            if (!paymentData.getCouponsList().get(i).getCouponsType().equals("serviceVoucher")) {
                if (couponList.contains("" + paymentData.getCouponsList().get(i).getUserWalletId())) {
                    paymentData.getCouponsList().get(i).setPicked(true);
                } else {
                    paymentData.getCouponsList().get(i).setPicked(false);
                }
            }
        }
    }
}
